﻿using System;
using System.Linq;
using System.Xml.Linq;

namespace RESTAgent.BasicMediaTypes.Hal {
    public class HalDocument {
        
        public HalResource Root { get; set; }

        public HalLink FindLink(string relationPath) {

            var halPath = new HalPath(relationPath);
            
            HalNode currentNode = Root;
            foreach (var segment in halPath.Segments) {
                if (currentNode is HalResource) {
                    if (String.IsNullOrEmpty(segment.Name)) {
                        currentNode = ((HalResource) currentNode).Contents[segment.Rel];
                    } else {
                        currentNode = ((HalResource)currentNode).Contents[segment.Rel + "["+ segment.Name + "]"];
                    }
                }
                
            }
            var halNode = currentNode;
            if (halNode is HalLink) return (HalLink)halNode;
            if (halNode is HalResource) {
                    var halLink = ((HalResource) halNode).ResourceLink;
                    //halLink.Name = halPath.Segments.Last().Name;
                    return halLink;
            }
            return null;
        }


        public static object Load(System.IO.Stream stream) {
            var element = XElement.Load(stream);

            var doc = new HalDocument() {
                Root = element.ReadAsHalResource()
            };

            return doc;
        }
    }
}
